﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static OPCPlatformConfigure.OracleHelper;

namespace OPCPlatformConfigure.BllBusiness.OPCUa
{
    public class bllOPCUa
    {
        OracleHelper oh;
        public bllOPCUa()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString;
            oh = new OracleHelper(connectionString);
        }
        public DataTable GetTags(string mainId)
        {
            string query = string.Format("select * from mda_opcuatags t where t.MAINGUID='{0}' order by t.id", mainId);
            return oh.GetTable(query);
        }
        public void DeleteTagsById(string mainId, bool needDeleteMachine = false)
        {
            if (needDeleteMachine)
            {
                string deleteMachines = string.Format("delete from mda_machines t where t.GUID='{0}'", mainId);
                oh.ExecuteNonQuery(deleteMachines);
            }
            string deleteTags = string.Format("delete from mda_opcuatags t where t.MAINGUID='{0}'", mainId);
            oh.ExecuteNonQuery(deleteTags);
        }
        public void InsertMahine(List<OracleParameterWrapper> datas, string machineName, string mainId = null)
        {
            String idTemp = Guid.NewGuid().ToString();
            //1.如果现在是修改,则首先删除原有的所有Tag,然后重新导入
            if (mainId != null)
            {
                DeleteTagsById(mainId);
            }
            //2.如果现在是新增,则首先插入Machine信息
            else
            {
                string machineSql = string.Format("insert into mda_machines(GUID,MACHINENAME,OPCTYPE)values('{0}','{1}',1)", idTemp, machineName);
                oh.ExecuteNonQuery(machineSql);
            }
            //3.插入Tag信息
            string insertTags = string.Format("Insert into mda_opcuatags t (FRIENDLYNAME,ADDRESS,DATATYPE,NEEDREAD,NEEDWRITE,MAINGUID)values(:FRIENDLYNAME,:ADDRESS,:DATATYPE,:NEEDREAD,:NEEDWRITE,'{0}')", mainId ?? idTemp);
            oh.InsertDataMany(insertTags, datas);
        }
    }
}
